package com.yuanfeng.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.business.dto.ApplyPayOnDeliveryRecordDTO;
import com.yuanfeng.business.dto.AuditDeliveryDTO;
import com.yuanfeng.business.dto.ManageSetShopParamQueryDTO;
import com.yuanfeng.business.dto.delivery.CheckShopDeliveryDTO;
import com.yuanfeng.business.dto.delivery.DeliveryShopQueryDTO;
import com.yuanfeng.business.dto.delivery.QueryIsDeliveryDTO;
import com.yuanfeng.business.dto.delivery.ShopSetDTO;
import com.yuanfeng.business.entity.ShopCashOnDeliveryEntity;
import com.yuanfeng.business.mapper.ShopBaseMapper;
import com.yuanfeng.business.mapper.ShopCashOnDeliveryMapper;
import com.yuanfeng.business.service.ShopCashOnDeliveryService;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ShopCashOnDeliveryServiceImpl
 * @Description 货到付款
 * @Author cyp
 * @Date 2023-05-26 17:20:34
 * @Version 1.0
 **/
@Service
public class ShopCashOnDeliveryServiceImpl extends ServiceImpl<ShopCashOnDeliveryMapper, ShopCashOnDeliveryEntity>
        implements ShopCashOnDeliveryService {

    @Resource
    private ShopBaseMapper shopBaseMapper;

    @Override
    public ResponseResult queryIsDelivery(QueryIsDeliveryDTO queryIsDeliveryDTO) {
        //根据token获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(queryIsDeliveryDTO.getToken());
        List<Integer> shopIdList = queryIsDeliveryDTO.getShopIdList();
        if (userInfo != null) {
            List<CheckShopDeliveryDTO> checkShopDeliveryDTOArrayList = new ArrayList<CheckShopDeliveryDTO>();
            Map<String, Object> param = new HashMap<>();
            for (Integer shopId : shopIdList) {
                CheckShopDeliveryDTO checkShopDeliveryDTO = new CheckShopDeliveryDTO();
                //根据shopId查询店铺是否有货到付款资格
                if (shopId != null) {
                    Integer count = this.baseMapper.queryCountSelectByShopId(shopId);
                    if (count == 0) {//未开通货到支付功能
                        checkShopDeliveryDTO.setIsDelivery(0);
                        param.put("isDelivery", 0);
                        return ResponseResult.success("尚未开通货到付款", param);
                    } else if (count == 1) {
                        DeliveryShopQueryDTO deliveryShopQueryDTO = this.baseMapper.queryShopSetDetialDelivery(shopId);
                        if (deliveryShopQueryDTO.getApplyStatus() == 2 || deliveryShopQueryDTO.getApplyStatus() == 3 || deliveryShopQueryDTO.getApplyStatus() == 5) {//已开通货到支付功能
                            checkShopDeliveryDTO.setIsDelivery(1);
                        } else {
                            checkShopDeliveryDTO.setIsDelivery(0);
                            param.put("isDelivery", 0);
                            return ResponseResult.success("尚未开通货到付款", param);
                        }
                    } else {
                        checkShopDeliveryDTO.setIsDelivery(999);
                        return ResponseResult.fail(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
                    }
                    checkShopDeliveryDTO.setShopId(shopId);
                }
                checkShopDeliveryDTOArrayList.add(checkShopDeliveryDTO);
            }
            param.put("isDelivery", 1);
            return ResponseResult.success("尚未开通货到付款", param);
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult queryShopSetDelivery(ShopSetDTO queryShopSetDTO) {
        //根据token获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(queryShopSetDTO.getToken());
        if (userInfo == null) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        //根据shopId查询店铺是否有申请货到付款记录
        if (userInfo.getShopId() != null) {
            queryShopSetDTO.setShopId(Integer.valueOf(userInfo.getShopId()));
        }
        Map<String, Object> param = new HashMap<>();
        Integer num = this.baseMapper.queryCountSelectByShopId(queryShopSetDTO.getShopId());
        if (num == 0) {
            //0从未申请开通的状态，页面展示申请开启
            param.put("open", 0);
            return ResponseResult.success(1, "初次申请", param);
        }
        DeliveryShopQueryDTO deliveryShopQueryDTO = this.baseMapper.queryShopSetDetialDelivery(queryShopSetDTO.getShopId());
        Integer applyStatus = deliveryShopQueryDTO.getApplyStatus();
        param.put("open", 1);
        param.put("applyStatus", applyStatus);
        param.put("reason", deliveryShopQueryDTO.getReason());
        param.put("platformReason", deliveryShopQueryDTO.getPlatformReason());
        return ResponseResult.success(1, "已存在申请记录", param);
    }

    @Override
    public ResponseResult applyPayOnDeliveryOn(ShopSetDTO applyPayOnDeliveryDTO) {
        //根据token获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(applyPayOnDeliveryDTO.getToken());
        if (userInfo == null) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        //根据shopId查询店铺是否有申请货到付款记录
        if (userInfo.getShopId() == null) {
            return ResponseResult.fail(2, "店铺id获取失败，请重新登录！");
        }
        Integer count = this.baseMapper.queryCountSelectByShopId(Integer.valueOf(userInfo.getShopId()));
        ApplyPayOnDeliveryRecordDTO applyPayOnDeliveryRecordDTO = new ApplyPayOnDeliveryRecordDTO();
        //根据shopId获取shopName
        ManageSetShopParamQueryDTO manageSetShopParamQuery = this.baseMapper.selectShopDetial(userInfo.getShopId());
        if (manageSetShopParamQuery == null && manageSetShopParamQuery.getShopName() == null) {
            return ResponseResult.fail(2, "无店铺信息");
        }
        applyPayOnDeliveryRecordDTO.setShopName(manageSetShopParamQuery.getShopName());
        if (count == 0) {
            //插入一条数据，并设置状态为1待审核
            applyPayOnDeliveryRecordDTO.setShopId(Integer.valueOf(userInfo.getShopId()));
            applyPayOnDeliveryRecordDTO.setUserId(userInfo.getUserId());
            applyPayOnDeliveryRecordDTO.setApplyStatus(1);
            applyPayOnDeliveryRecordDTO.setReason(applyPayOnDeliveryDTO.getText());
            Integer result = this.baseMapper.insertApplyPayOnDeliveryRecord(applyPayOnDeliveryRecordDTO);
            if (result == 1) {
                return ResponseResult.success(1, "已成功提交申请");
            }
        } else if (count == 1) {//更新数据，分为两种情况，若传入为1
            //插入一条数据，并设置状态为1待审核
            applyPayOnDeliveryRecordDTO.setShopId(Integer.valueOf(userInfo.getShopId()));
            applyPayOnDeliveryRecordDTO.setUserId(userInfo.getUserId());
            if (applyPayOnDeliveryDTO.getStatus() == 1) {//重复设为开启
                applyPayOnDeliveryRecordDTO.setApplyStatus(applyPayOnDeliveryDTO.getStatus());
            } else if (applyPayOnDeliveryDTO.getStatus() == 0) {//设为关闭
                applyPayOnDeliveryRecordDTO.setApplyStatus(3);
            }
            applyPayOnDeliveryRecordDTO.setReason(applyPayOnDeliveryDTO.getText());
            Integer result = this.baseMapper.updateApplyPayOnDeliveryRecord(applyPayOnDeliveryRecordDTO);
            if (result == 1) {
                return ResponseResult.success(1, "已成功提交申请（更新）");
            }
            return ResponseResult.fail(2, "提交审核失败");
        }
        return ResponseResult.fail(2, "数据异常，请联系数据库管理员！");
    }

    @Override
    public ResponseResult auditDelivery(AuditDeliveryDTO param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(param.getToken());
        if (userInfoVO==null) {
            return ResponseResult.success(BizCodeEnume.TOKEN_IS_INVALID);
        }
        if (param.getShopId() != null) {
            //查询出当前店铺的状态
            ShopCashOnDeliveryEntity deliveryShopQueryDTO = this.getOne(new LambdaQueryWrapper<ShopCashOnDeliveryEntity>()
                    .eq(ShopCashOnDeliveryEntity::getShopId, param.getShopId()));
            LambdaUpdateWrapper<ShopCashOnDeliveryEntity> updateWrapper = new LambdaUpdateWrapper<>();
            //设置更新
            updateWrapper.set(ShopCashOnDeliveryEntity::getUpdateTime, DateUtils.getTime());
            updateWrapper.set(ShopCashOnDeliveryEntity::getPlatformReason, param.getReason());
            //通过申请
            if (param.getIsAgree() == 1) {
                //同意开通
                if (deliveryShopQueryDTO.getApplyStatus().equals(CommonType.deliveryApplyStatus.OPEN_TO_BE_REVIEWED.getCode())) {
                    updateWrapper.set(ShopCashOnDeliveryEntity::getApplyStatus, CommonType.deliveryApplyStatus.APPROVED.getCode());
                    //同意关闭
                } else if (deliveryShopQueryDTO.getApplyStatus().equals(CommonType.deliveryApplyStatus.OFF_TO_BE_REVIEWED.getCode())) {
                    updateWrapper.set(ShopCashOnDeliveryEntity::getApplyStatus, CommonType.deliveryApplyStatus.OPEN_FAILED_TO_REVIEW.getCode());
                }
                //拒绝申请
            } else {
                //拒绝开通
                if (deliveryShopQueryDTO.getApplyStatus().equals(CommonType.deliveryApplyStatus.OPEN_TO_BE_REVIEWED.getCode())) {
                    updateWrapper.set(ShopCashOnDeliveryEntity::getApplyStatus, CommonType.deliveryApplyStatus.NOT_APPLIED.getCode());
                    //拒绝关闭
                } else if (deliveryShopQueryDTO.getApplyStatus().equals(CommonType.deliveryApplyStatus.OFF_TO_BE_REVIEWED.getCode())) {
                    updateWrapper.set(ShopCashOnDeliveryEntity::getApplyStatus, CommonType.deliveryApplyStatus.OFF_FAILED_TO_REVIEW.getCode());
                }
            }
            updateWrapper.eq(ShopCashOnDeliveryEntity::getShopId, param.getShopId());
            boolean flag = this.update(updateWrapper);
            if (flag) {
                return ResponseResult.success();
            }
            return ResponseResult.fail(BizCodeEnume.REJECT_APPLY);
        }
        return ResponseResult.fail(BizCodeEnume.NO_STORE_INFORMATION);
    }

    @Override
    public ResponseResult queryDeliveryShop(Map<String, Object> param) {
        //设置查询参数
        LambdaQueryWrapper<ShopCashOnDeliveryEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (param.containsKey("shopName")&&!"".equals(param.get("shopName"))) {
            queryWrapper.like(ShopCashOnDeliveryEntity::getShopName, param.get("shopName").toString());
        }
        if (param.containsKey("status")&&param.get("status") != null) {
            queryWrapper.like(ShopCashOnDeliveryEntity::getApplyStatus, param.get("status").toString());
        }
        //排序
        queryWrapper.orderByDesc(ShopCashOnDeliveryEntity::getUpdateTime);
        //分页查询
        if (param.containsKey("page")&&param.get("page") != null &&param.containsKey("limit")&&param.get("limit") != null) {
            Page<ShopCashOnDeliveryEntity> page = new Page<>(Integer.valueOf(param.get("page").toString()),Integer.valueOf(param.get("limit").toString()));
            IPage<ShopCashOnDeliveryEntity> results = this.page(page, queryWrapper);
            return ResponseResult.success(PageUtils.getPage(results));
        }
        //全部查询
        List<ShopCashOnDeliveryEntity> list = this.list(queryWrapper);
        return ResponseResult.success(list);
    }
}
